package com.zijidelu.luframework.infrastructure.factory.impl;

import com.zijidelu.luframework.base.TypeCaster;
import com.zijidelu.luframework.base.model.DataModel;
import com.zijidelu.luframework.base.model.PO;
import com.zijidelu.luframework.domain.model.entity.Entity;
import com.zijidelu.luframework.infrastructure.converter.AggregateConverter;
import com.zijidelu.luframework.infrastructure.converter.DataConverter;
import com.zijidelu.luframework.infrastructure.factory.ConverterVault;
import com.zijidelu.luframework.utils.cache.vault.AbstractGroupedVault;
import com.zijidelu.luframework.utils.cache.vault.ItemVault;
import com.zijidelu.luframework.utils.cache.vault.SimpleVaultGroup;
import org.springframework.stereotype.Component;

/**
 * 转换器缓存实现类。
 *
 * @author ZIJIDELU
 * @datetime 2025/11/27 14:53
 */
@Component
public class ConverterVaultImpl extends AbstractGroupedVault<SimpleVaultGroup, Object, Object> implements ConverterVault {
    /**
     * 聚合转换器缓存。
     * <p>
     * 缓存Key为实体Class，Value为聚合转换器。
     */
    private ItemVault<Class<?>, AggregateConverter<?, ?, ?>> aggregateConverterMap() {
        return getItem(SimpleVaultGroup.GROUP_0).selfCast();
    }

    /**
     * 数据转换器缓存。
     * <p>
     * 缓存Key为实体Class，Value为数据转换器。
     */
    private ItemVault<Class<?>, DataConverter<?, ?>> dataConverterMap() {
        return getItem(SimpleVaultGroup.GROUP_1).selfCast();
    }

    @Override
    public AggregateConverter<?, ?, ?> registerAggregateConverter(Class<?> clazz, AggregateConverter<?, ?, ?> converter) {
        // 校验clazz是否为Entity类的子类
        if (!Entity.class.isAssignableFrom(clazz)) {
            return null;
        }

        aggregateConverterMap().put(clazz, converter);
        return converter;
    }

    @Override
    public <P extends PO, D extends DataModel, E extends Entity<D>> AggregateConverter<P, D, E> getAggregateConverter(Class<?> clazz) {
        return TypeCaster.cast(aggregateConverterMap().get(clazz));
    }


    @Override
    public DataConverter<?, ?> registerDataConverter(Class<?> clazz, DataConverter<?, ?> converter) {
        // 校验clazz是否为PO类和DataModel类的子类
        if (!PO.class.isAssignableFrom(clazz) || !DataModel.class.isAssignableFrom(clazz)) {
            return null;
        }

        dataConverterMap().put(clazz, converter);
        return converter;
    }

    @Override
    public <P extends PO, D extends DataModel> DataConverter<P, D> getDataConverter(Class<?> clazz) {
        return TypeCaster.cast(dataConverterMap().get(clazz));
    }
}
